<template>
  <div class="container">
    <div class="filter-container">
      <el-form ref="listQuery" :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-select v-model="listQuery.id" filterable="" @change="areaChange">
            <el-option v-for="(item ,index) in area_list" :key="index" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">重置周期：{{area_info.interval_month}}个月</el-form-item>
        <el-form-item>
          <el-button type="primary" plain size="middle" @click="editArea()" v-if="controlBtn.edit">编辑当前区域</el-button>
          <el-button type="primary" size="middle" @click="addArea()" v-if="controlBtn.add">添加区域</el-button>
          <el-button type="danger" size="middle" @click="deleteArea()" v-if="controlBtn.add">删除当前区域</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="middle">
      <div class="flex-row">
        <!-- <el-button type="primary" plain size="middle" @click="search()">上传巡检储罐照片</el-button> -->
        <el-upload v-if="controlBtn.add"
          class="avatar-uploader"
          :action="fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :headers="headers"
          :before-upload="beforeAvatarUpload">
          <el-button type="primary" plain size="middle">上传巡检储罐照片</el-button>
        </el-upload>
        <el-button type="primary" size="middle" @click="addStorage()">添加储罐标记</el-button>
      </div>
      <div class="content no_height" :class="{'show_img':area_info.image_url && area_info.image_url.length>0}">
        <img id="img" style="width:100%; height:100%;" :src="area_info.image_url" alt="">
        <canvas ref="markCanvas" tabindex='0'></canvas>
      </div>
      <div class="flex-row align-center">
        <div class="flex-1">舱口列表</div>
        <div>储罐编号
          <el-select v-model="storage_id" filterable=""  @change="change">
            <el-option v-for="(item ,index) in storage_list" :key="index" :label="item.code" :value="item.id"></el-option>
          </el-select>
        </div>
        <el-button style="margin-left:10px" type="danger" size="middle" @click="deleteStorage()" v-if="controlBtn.del">删除储罐</el-button>
        <el-button style="margin-left:10px" type="primary" size="middle" @click="addHatch()" v-if="controlBtn.add">添加舱口</el-button>
      </div>
    </div>
    <el-table v-loading="loading"
    :data="hatch_list"
    border
    style="width: 90%">

    <el-table-column
      prop="storage_code"
      align="center"
      label="储罐编号"
      width="80">
    </el-table-column>
    <el-table-column
      prop="code"
      label="舱口编号"
      align="center"
    >
    </el-table-column>
    <el-table-column
      prop="last_date"
      label="最后巡检时间"
      align="center"
    >
    </el-table-column>
    <el-table-column
      prop="is_polling"
      label="巡检状态"
      align="center"
      >
      <template slot-scope="{row}"><span>{{{'10':'巡检正常','20':'有异常','30':'未巡检'}[row.is_polling]}}</span></template>
    </el-table-column>
    <el-table-column
      align="center"
      width="180"
      label="操作">
      <template slot-scope="{row}">
        <el-button type="primary" size="small" @click="editHatch(row)" v-if="controlBtn.edit">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteHatch(row)" v-if="controlBtn.del">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加、编辑储罐 -->
  <el-dialog class="dialogVisible dia" :title="dialogVisible.dia_title" :visible.sync='dialogVisible.show' :close-on-click-modal=false>
    <el-form :rules="rulesStorage" :model="dialogVisible" ref="storageForm" label-position="top" class="dialogVisible">
       <div class="flex-row">
        <el-form-item class="flex-1" style="margin-right:10px" label="储罐编号" prop="code">
          <el-input v-model="dialogVisible.code" type="number" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item class="flex-1" style="margin-right:10px" label="舱口起始编号" prop="start_num">
          <el-input v-model="dialogVisible.start_num" type="number" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item class="flex-1" label="舱口数量" prop="num">
          <el-input v-model="dialogVisible.num" type="number" placeholder="" clearable></el-input>
        </el-form-item>
       </div>
       <el-form-item v-if="area_info.image_url && area_info.image_url.length>0">
          <div class="server">选择储罐区域</div>
          <div class="content show_img">
            <img id="img" style="width:100%; height:100%;" :src="area_info.image_url" alt="">
            <canvas ref="storageCanvas"></canvas>
          </div>
       </el-form-item>
      <el-form-item style="margin-bottom:0">
        <el-button type="default" @click="dialogVisible.show=false">取消</el-button>
        <el-button type="primary" @click="dialogSubmit()">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 添加编辑区域 -->
    <el-dialog close class="diagArea dia" :title="areaDialogVisible.dia_title" :visible.sync='areaDialogVisible.show' :close-on-click-modal=false>
      <el-form :rules="rules" :model="areaDialogVisible" ref="areaDialogVisible" label-position="top" class="areaDialogVisible">
       <div class="flex-row">
        <el-form-item class="flex-1" label="区域名称" prop="title">
          <el-input type="text" v-model="areaDialogVisible.title" placeholder="" clearable></el-input>
        </el-form-item>
        <el-form-item style="width:200px;margin-left:10px" label="重置周期（月）" prop="interval_month">
          <!-- <el-input type="number"  v-model="areaDialogVisible.interval_month" placeholder="" clearable></el-input> -->
          <el-input-number v-model="areaDialogVisible.interval_month" :min="1" :max="12"></el-input-number>
        </el-form-item>
       </div>
        <el-form-item>
          <el-button type="default" @click="areaDialogVisible.show=false">取消</el-button>
          <el-button type="primary" @click="areaSubmit()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加编辑舱口 -->
    <el-dialog close class="diagArea dia" :title="hatchDialogVisible.dia_title" :visible.sync='hatchDialogVisible.show' :close-on-click-modal=false>
      <el-form :rules="rulesHatch" :model="hatchDialogVisible" ref="hatchForm" label-position="top" class="areaDialogVisible">
       <div class="flex-row">
        <el-form-item class="flex-1" label="储罐编号" prop="storage_id">
          <el-select v-model="hatchDialogVisible.storage_id" filterable="">
            <el-option v-for="(item ,index) in storage_list" :key="index" :label="item.code" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="flex-1" style="margin-left:10px" label="舱口编号" prop="code">
            <el-input type="number" v-model="hatchDialogVisible.code" placeholder="" clearable></el-input>
        </el-form-item>
       </div>
        <el-form-item>
          <el-button type="default" @click="hatchDialogVisible.show=false">取消</el-button>
          <el-button type="primary" @click="hatchSubmit()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { user_list, user_save, user_delete } from '@/api/system'
import {  area_info,area_save,storage_list,storage_delete,storage_info,storage_save,hatch_list,hatch_save,hatch_delete,area_delete } from '@/api/server'
import { draw } from "@/utils/draw"; // 矩形绘制方法

import { area_list } from '@/api/bigdata'
import { getToken } from '@/utils/auth' // get token from cookie
import store from '@/store'

  export default {
    data() {
      return {
        tableData: [],
        listQuery:{
          id:''
        },
        fileUpload: `${process.env.VUE_APP_BASE_API}/file/upload`,
        storage_id:'',
        storage_list:[],
        hatch_list:[],
        area_info:{},
        loading:false,
        roleList:[],
        dialogVisible:{
          show:false,
          dia_title:'创建储罐标记',
          code:'',
          id:0,
          pos_x:'',
          pos_y:'',
          width:'',
          height:'',
          area_id:'',
          start_num:'',
          num:'',
          id:0
        },
        areaDialogVisible:{
          show:false,
          dia_title:'添加区域',
          title:'',
          interval_month:'',
          image_url:'',
          image_width:'',
          image_height:'',
          id:0
        },
        rules:{
          title:[{required:true,message:'区域名称不能为空',trigger: 'blur'}],
          interval_month:[{required:true,message:'重置周期不能为空',trigger: 'blur'}],
          code:[{required:true,message:'储罐编号不能为空',trigger: 'blur'}],
          start_num:[{required:true,message:'舱口起始编号不能为空',trigger: 'blur'}],
          num:[{required:true,message:'舱口数量不能为空',trigger: 'blur'}]
        },
        rulesStorage:{
          code:[{required:true,message:'储罐编号不能为空',trigger: 'blur'}],
          start_num:[{required:true,message:'舱口起始编号不能为空',trigger: 'blur'}],
          num:[{required:true,message:'舱口数量不能为空',trigger: 'blur'}]
        },
        hatchDialogVisible:{
          show:false,
          dia_title:'添加舱口',
          storage_id:'',
          code:'',
          id:0
        },
        rulesHatch:{
          storage_id:[{required:true,message:'储罐编号不能为空',trigger: 'blur'}],
          code:[{required:true,message:'舱口编号不能为空',trigger: 'blur'}]
        },
        area_list:[],
        markList: [], // 标记内容数组,
        storageList:[],
        controlBtn:{
          add:false,
          del:false,
          edit:false,
          auth:false
        }
      }
    },
    computed: {
      headers(){
        return {
          'Authorization':getToken()
        }
      }
    },
    methods:{
      handleAvatarSuccess(res, file) {
        // this.imageUrl = URL.createObjectURL(file.raw);
        console.log(res,file)
        let url  = res.body.url
        this.$set(this.area_info,'image_url',url)
        //
        let that = this
        let newList = JSON.parse(JSON.stringify(that.area_info))
            newList.id = parseInt(that.area_info.id)
            newList.interval_month = parseInt(that.area_info.interval_month)
            newList.image_width = 728
            newList.image_height = 490
            that.areaDialogVisible.show=false
            area_save(newList).then(res=>{
              // this.getAreaList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              setTimeout(() => {
                that.getAreaInfo()
              }, 2000);
            })
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        // const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!');
        // }
        // return isJPG && isLt2M;
      },
      deleteHatch(row){
        let that = this
        this.$confirm('确实删除当前舱口吗？','提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消'
        }).then(()=>{
          hatch_delete({id:parseInt(row.id)}).then(res=>{
              // this.getAreaList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              setTimeout(() => {
                that.getHatchList()
              }, 2000);
            })
        })

      },
      hatchSubmit(){
        let that = this
        this.$refs['hatchForm'].validate((valid)=>{
          if(valid){
            let newList = JSON.parse(JSON.stringify(that.hatchDialogVisible))
            newList.id = parseInt(that.hatchDialogVisible.id)
            newList.code = parseInt(that.hatchDialogVisible.code)
            newList.storage_id = parseInt(that.hatchDialogVisible.storage_id)
            that.hatchDialogVisible.show=false
            hatch_save(newList).then(res=>{
              // this.getAreaList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              setTimeout(() => {
                that.getHatchList()
              }, 2000);
            })
          }
        })
      },
      addHatch(){
        this.hatchDialogVisible.dia_title='添加舱口'
        this.hatchDialogVisible.code=''
        this.hatchDialogVisible.storage_id= this.storage_id
        this.hatchDialogVisible.id=0
        this.hatchDialogVisible.show=true
      },
      editHatch(row){
        this.hatchDialogVisible.dia_title='编辑舱口'
        this.hatchDialogVisible.code=row.code
        this.hatchDialogVisible.storage_id=row.storage_id
        this.hatchDialogVisible.id=row.id
        this.hatchDialogVisible.show=true
      },
      areaChange(e){
        this.listQuery.id = e
          this.getAreaInfo()
      },
      deleteStorageInfo(){
        storage_delete({id:this.storage_id}).then(res=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        setTimeout(() => {
            this.storage_id = ''
            this.getStorageList()
          }, 2000);
        })
      },
      change(e){
        // console.log(e)
        this.storage_id = e
        this.getHatchList()
      },
      deleteStorage(){
        let that = this
        if(!this.storage_id){
          this.$message.error('请先选择储罐！');
          return
        }
        this.$confirm('是否要删除该储罐, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          that.deleteStorageInfo()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
       /* 画布初始化 */
    initCanvas() {
      let that = this
      this.$nextTick(() => {
        // 初始化canvas宽高
        let cav = this.$refs.markCanvas;
        cav.width = that.area_info.image_width;
        cav.height = that.area_info.image_height;
        let ctx = cav.getContext('2d');
        ctx.strokeStyle = 'yellow'
        cav.style.cursor = 'pointer'

        // 计算使用变量
        let list = this.markList; // 画框数据集合, 用于服务端返回的数据显示和绘制的矩形保存
        // 若服务端保存的为百分比则此处需计算实际座标, 直接使用实际座标可省略
        list.forEach(function (value, index, array) {
          let newValue = {
            x: value.x,
            y: value.y,
            w: value.w,
            h: value.h,
          }
          list.splice(index, 1, newValue)
        })

        // 若list长度不为0, 则显示已标记框
        if (list.length !== 0) {
          list.forEach(function (value, index, array) {
            // 遍历绘制所有标记框
            ctx.beginPath();
            ctx.ellipse(value.x + value.w / 2, value.y + value.h / 2, value.w / 2, value.h / 2, 0, 0, Math.PI * 2);
            ctx.lineWidth = 2;
            ctx.strokeStyle = 'yellow';
            ctx.fillStyle = 'rgba(255, 255, 0, 0.3)';
            ctx.fill();
            
            // ctx.arc(value.x, value.y, 4, 0, Math.PI * 2)

            // ctx.fillRect(value.x, value.y, value.w, value.h);
            ctx.stroke();
          });

        }
        this.drawStorage(cav,list)
        // 调用封装的绘制方法
        // draw(cav, list);

        // 备注: js中对象操作指向的是对象的物理地址, 获取绘制完矩形的结果数组直接取用或处理this.markList即可
      })
    },
    drawStorage(cav, list, i) {
    /*
     *鼠标移动进行第一层判断, 区分情况: 无矩形, 已有矩形无选中, 已有选中矩形
     */
    let that = this
     cav.onmousedown = function(em) {
          let sX = em.offsetX; // 起点X坐标
          let sY = em.offsetY; // 起点Y坐标
          let iem = null
            console.log(sX, sY)
            // 判断鼠标位置
            list.forEach(function(value, index, array) {
                if (value.w > 0 && value.h > 0 && sX > value.x && sX < value.x + value.w && sY > value.y && sY < value.y + value.h) {
                    // 鼠标在右下方向生成的矩形中
                    iem = index;
                    // judgeDraw(cav, ctx, list, iem);
                    that.changeStorage(iem)

                }
                if (value.w < 0 && value.h > 0 && sX < value.x && sX > value.x + value.w && sY > value.y && sY < value.y + value.h) {
                    // 鼠标在左下方向生成的矩形中
                    iem = index;
                    // judgeDraw(cav, ctx, list, iem);
                    that.changeStorage(iem)

                }
                if (value.w > 0 && value.h < 0 && sX > value.x && sX < value.x + value.w && sY < value.y && sY > value.y + value.h) {
                    // 鼠标在右上方向生成的矩形中
                    iem = index;
                    // judgeDraw(cav, ctx, list, iem);
                    that.changeStorage(iem)

                }
                if (value.w < 0 && value.h < 0 && sX < value.x && sX > value.x + value.w && sY < value.y && sY > value.y + value.h) {
                    // 鼠标在左上方向生成的矩形中
                    iem = index;
                    // judgeDraw(cav, ctx, list, iem);
                    that.changeStorage(iem)

                }
            })
    }

    // console.log(cav, list, i);

    },

    initStorageCanvas() {
      let that = this
      this.$nextTick(() => {
        // 初始化canvas宽高
        let cav = this.$refs.storageCanvas;
        cav.width = 728;
        cav.height = 490;
        // 计算使用变量
        let list = this.storageList; // 画框数据集合, 用于服务端返回的数据显示和绘制的矩形保存
        // 调用封装的绘制方法
        draw(cav, list, 1);

        // 备注: js中对象操作指向的是对象的物理地址, 获取绘制完矩形的结果数组直接取用或处理this.markList即可
      })
    },
    changeStorage(iem){
      let item = this.storage_list[iem]
      console.log(item.id)
      this.storage_id = item.id
      this.getHatchList()
    },
    addStorage(){
      this.storageList = []
      this.dialogVisible.code=''
        this.dialogVisible.pos_x=''
        this.dialogVisible.pos_y=''
        this.dialogVisible.width=''
        this.dialogVisible.height=''
        this.dialogVisible.area_id=this.listQuery.id
        this.dialogVisible.start_num=''
        this.dialogVisible.num=''
        this.dialogVisible.id=0
        this.dialogVisible.show=true
      this.$nextTick(()=>{
        this.initStorageCanvas()
      })
    },
    areaSubmit(){
      let that = this
      this.$refs['areaDialogVisible'].validate((valid)=>{
          if(valid){
            let newList = JSON.parse(JSON.stringify(that.areaDialogVisible))
            newList.id = parseInt(that.areaDialogVisible.id)
            newList.interval_month = parseInt(that.areaDialogVisible.interval_month)
            newList.image_width = parseInt(that.areaDialogVisible.image_width)
            newList.image_height = parseInt(that.areaDialogVisible.image_height)
            that.areaDialogVisible.show=false
            area_save(newList).then(res=>{
              // this.getAreaList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              setTimeout(() => {
                that.getAreaList()
              }, 2000);
            })
          }
        })
    },
      editArea(){
        this.areaDialogVisible.dia_title='编辑区域'
        this.areaDialogVisible.title=this.area_info.title
        this.areaDialogVisible.interval_month=this.area_info.interval_month
        this.areaDialogVisible.image_url=this.area_info.image_url
        this.areaDialogVisible.image_width=this.area_info.image_width
        this.areaDialogVisible.image_height=this.area_info.image_height
        this.areaDialogVisible.id=this.area_info.id
        this.areaDialogVisible.show=true
      },
      deleteArea(){
        let that = this
        this.$confirm('确实删除当前区域吗？','提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消'
        }).then(()=>{
          area_delete({id:parseInt(that.area_info.id)}).then(res=>{
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              setTimeout(() => {
                that.getAreaList()
              }, 1000);
            })
        })
      },
      addArea(){
        this.areaDialogVisible.dia_title='添加区域'
        this.areaDialogVisible.title=''
        this.areaDialogVisible.interval_month=''
        this.areaDialogVisible.image_url=''
        this.areaDialogVisible.image_width=''
        this.areaDialogVisible.image_height=''
        this.areaDialogVisible.id=0
        this.areaDialogVisible.show=true
      },
      dialogSubmit(){
        // console.log(this.storageList)
        if(this.storageList.length == 0){
          this.$message({
            message: '请在地图上添加储罐标记',
            type: 'warning'
           });
        }else if(this.storageList.length >1){
          this.$message({
            message: '每次只能添加一个储罐标记',
            type: 'warning'
           });
        }else{
          let that = this
          this.$refs['storageForm'].validate((valid)=>{
            if(valid){
              let item = that.storageList[0]
              let newList = JSON.parse(JSON.stringify(that.dialogVisible))
              newList.id = parseInt(that.dialogVisible.id)
              // newList.code = parseInt(that.dialogVisible.code)
              newList.area_id = parseInt(that.dialogVisible.area_id)
              newList.start_num = parseInt(that.dialogVisible.start_num)
              newList.num = parseInt(that.dialogVisible.num)
              newList.pos_x = parseInt(item.x)
              newList.pos_y = parseInt(item.y)
              newList.width = parseInt(item.w)
              newList.height = parseInt(item.h)

              storage_save(newList).then(res=>{
                console.log(res)
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                that.dialogVisible.show=false
                that.getStorageList()
              })
            }
          })
        }

      },
      getAreaInfo(){
        area_info(this.listQuery).then(res=>{
          this.area_info = res
          this.getStorageList()
        })
      },
      getStorageList(){
        let that = this
        storage_list({area_id:this.listQuery.id}).then(res=>{
          this.storage_list = res
          let arr = []
          this.storage_list.forEach(e=>{
            // console.log(e.pos_x,e.pos_y)
            let obj = {}
            that.$set(obj,'x',e.pos_x)
            that.$set(obj,'y',e.pos_y)
            that.$set(obj,'w',e.width)
            that.$set(obj,'h',e.height)
            console.log(obj)
            // arr.push(obj)
            arr.push(obj) // 创建一个新对象并将其添加到数组中

          })
          this.markList = arr
          // this.markList = arr.map(e=>{
          //   console.log(JSON.parse(e))
          //   return JSON.parse(e)
          // })
          // this.markList = arr
          // console.log(this.markList)

          // console.log(this.storage_list,this.markList,arr,'≠≠≠≠≠≠≠≠')
          this.$nextTick(()=>{
            this.initCanvas(); // 画布初始化
          })
          this.getHatchList()

        })
      },
      getHatchList(){
        this.loading = true
        hatch_list({area_id:this.listQuery.id,storage_id:this.storage_id}).then(res=>{
          this.hatch_list = res
          this.loading = false
        })
      },
      getAreaList(){
        area_list().then(res=>{
        this.area_list = res
        if(this.area_list && this.area_list.length>0){
          this.listQuery.id = this.area_list[0].id
          this.getAreaInfo()
        }
      })
      },

    },
    mounted(){
      this.getAreaList()
      const mainRoutes = store.getters.mainRoutes
      if(mainRoutes.inspection && mainRoutes.inspection.length>0){
        mainRoutes.inspection.forEach(e=>{
          if(e == '增加'){
            this.controlBtn.add = true
          }
          if(e == '删除'){
            this.controlBtn.del = true
          }
          if(e == '修改'){
            this.controlBtn.edit = true
          }
          if(e == '权限'){
            this.controlBtn.auth = true
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialogVisible {
    ::v-deep.el-form-item__label{
      padding: 0 !important;
    }
    ::v-deep.el-dialog__body { padding: 5px 20px; }
  }
  .middle { width: 90%; font-size: 14px; color: #666; padding-bottom: 10px; }
  .content {
    position: relative;

    img {
      z-index: 9;
    }

    canvas {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 10;
    }
  }
  .diagArea{
    ::v-deep.el-dialog { width:30% !important; }
  }
  .dialogVisible{
    ::v-deep.el-dialog { width:840px !important; }
  }
  .server { background: #f0f0f0; padding: 10px 15px; margin-bottom: 10px; }
  .avatar-uploader { margin-right: 10px; }
  .show_img { width:728px; height:490px !important; margin-top:10px;margin-bottom:10px; }
  .no_height { height: 0px; }
</style>
